import React, { Component } from 'react';
import { Cascader } from 'antd';
import city from './data';
// import { getCity } from '@/utils/utils';

interface SRCitySelectProps {
  //  监听选择
  onChange?: (value: any[]) => void;
  // 获取选择值
  getSelectedValues?: (value: any[]) => void;
  value?: any[];
  // 默认值
  defaultValue?: any[];
  cityCode?: string;
  setValue?: any[];
}
interface SRCitySelectState {
  city: any[];
  sValue: any[];
}

class SRCitySelect extends Component<SRCitySelectProps, SRCitySelectState> {
  constructor(props: SRCitySelectProps) {
    super(props);

    this.state = {
      city: [],
      sValue: props.setValue || [],
    };
  }

  onCascaderChange = (selectedValues: any) => {
    const { onChange, getSelectedValues } = this.props;
    const result: any[] = [];
    // 递归查询城市所有数据
    // function findCityData(c: any[]) {
    //   c.forEach((item: any) => {
    //     const { id, label, value, children } = item;
    //     if (selectedValues.includes(value)) {
    //       result.push({ id, label, value });
    //     }
    //     if (children && children.length) {
    //       findCityData(children);
    //     }
    //   });
    // }
    // if (selectedValues) {
    //   findCityData(city);
    // }

    this.setState({ sValue: selectedValues });
    // 分发监听
    if (onChange) {
      onChange(selectedValues);
    }
    if (getSelectedValues) {
      getSelectedValues(result);
    }
  };

  componentDidMount() {
    const { value: selectedValues, onChange } = this.props;

    this.setState({
      sValue: selectedValues || [],
    });

    if (onChange) {
      onChange(selectedValues || []);
    }
  }

  static getDerivedStateFromProps(props: any, current_state: any) {
    
    if (props.setValue && props.setValue.length > 0) {
      if (current_state.sValue.length > 0) {
        if (props.setValue[0] !== current_state.sValue[0]) {
          if (props.onChange) {
            props.onChange(props.setValue);
          }
          return {
            sValue: props.setValue,
          };
        }
      } else {
        if (props.onChange) {
          props.onChange(props.setValue);
        }
        return {
          sValue: props.setValue,
        };
      }
    }
    return null;
  }

  render() {
    // const { cityCode } = this.props;
    const { sValue } = this.state;
    return (
      <div>
        <Cascader
          options={city}
          placeholder="请选择区县"
          value={sValue}
          onChange={this.onCascaderChange}
        />
      </div>
    );
  }
}

export default SRCitySelect;
